package com.petshop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.petshop.mapper.LikesMapper;
import com.petshop.pojo.Likes;
import com.petshop.service.LikesService;
import com.petshop.utils.JwtHelper;
import com.petshop.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 20289
 * @description 针对表【likes(存储用户对帖子的点赞信息)】的数据库操作Service实现
 * @createDate 2025-02-27 11:17:00
 */
@Service
public class LikesServiceImpl extends ServiceImpl<LikesMapper, Likes>
        implements LikesService {
    @Autowired
    private LikesMapper likesMapper;

    @Autowired
    private JwtHelper jwtHelper;

    /**
     * 点赞与取消点赞的切换
     *
     * @param postId
     * @return
     */
    @Override
    public Result toggleLike(Integer postId, String token) {
        Integer userId = jwtHelper.getUserId(token).intValue();
        LambdaQueryWrapper<Likes> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Likes::getPostId, postId)
                .eq(Likes::getUserId, userId);
        Long count = likesMapper.selectCount(lambdaQueryWrapper);
        //如果已经点赞了，就取消点赞
        if (count > 0) {
            // 取消点赞
            likesMapper.delete(lambdaQueryWrapper);
            return Result.ok("已取消点赞！");
        }
        //如果没有点赞，就点赞
        else {
            // 点赞
            Likes likes = new Likes();
            likes.setPostId(postId);
            likes.setUserId(userId);
            likesMapper.insert(likes);
            return Result.ok("点赞成功");
        }
    }


    /**
     * 根据帖子的id获取帖子的获赞数量
     *
     * @param postId
     * @return
     */
    @Override
    public Result getLike(String postId) {
        LambdaQueryWrapper<Likes> lambdaQueryWrapper
                = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Likes::getPostId, postId);
        Long count = likesMapper.selectCount(lambdaQueryWrapper);
        return Result.ok(count);
    }
}




